package com.atguigu.gmall.list.controller;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.list.service.SearchService;
import com.atguigu.gmall.model.list.Goods;
import com.atguigu.gmall.model.list.SearchParam;
import com.atguigu.gmall.model.list.SearchResponseVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @author tongatong
 * @name ListApiController
 * @description
 * @date 2021/9/17
 * @time 15:43
 */
@Api(tags = "商品检索")
@RestController
@RequestMapping("api/list")
public class ListApiController {
    @Resource
    private ElasticsearchRestTemplate restTemplate;
    @Resource
    private SearchService searchService;

    @ApiOperation("创建索引和映射")
    @GetMapping("inner/createIndex")
    public Result<Void> createIndex() {
//        restTemplate.createIndex(Goods.class);
//        restTemplate.putMapping(Goods.class);
        IndexOperations indexOperations = restTemplate.indexOps(Goods.class);
        //创建索引
        indexOperations.create();
        //创建映射，然后将映射写入索引
        indexOperations.putMapping(indexOperations.createMapping(Goods.class));
        return Result.ok();
    }

    /**
     * 上架商品
     * @param skuId skuId
     * @return 结果信息
     */
    @ApiOperation("上架商品")
    @GetMapping("inner/upperGoods/{skuId}")
    public Result<Void> upperGoods(@PathVariable("skuId") Long skuId) {
        searchService.upperGoods(skuId);
        return Result.ok();
    }

    /**
     * 下架商品
     * @param skuId skuId
     * @return 结果信息
     */
    @ApiOperation("下架商品")
    @GetMapping("inner/lowerGoods/{skuId}")
    public Result<Void> lowerGoods(@PathVariable("skuId") Long skuId) {
        searchService.lowerGoods(skuId);
        return Result.ok();
    }

    /**
     * 更新商品incrHotScore
     *
     * @param skuId skuId
     * @return 结状态信息
     */
    @ApiOperation("更新商品incrHotScore")
    @GetMapping("inner/incrHotScore/{skuId}")
    public Result<Void> incrHotScore(@PathVariable("skuId") Long skuId) {
        // 调用服务层
        searchService.incrHotScore(skuId);
        return Result.ok();
    }

    /**
     * 搜索商品
     * 这里不一定传递那个列表的id，因此需要传递一个SearchParam
     * 因此需要使用@RequestBody注解来接受参数
     *
     * @param searchParam 前台获取的搜索信息
     * @return 返给前台的信息
     * @throws IOException 异常信息
     */
    @ApiOperation("搜索商品")
    @PostMapping
    public Result<SearchResponseVo> list(@RequestBody SearchParam searchParam) throws IOException {
        SearchResponseVo response = searchService.search(searchParam);
        return Result.ok(response);
    }



}
